package com.xbongbong.paas.toolbox.util;

import java.math.BigDecimal;

/**
 * 经纬度计算两个点的之间的距离
 *
 * @author 李杰
 * @version v1.0
 * @date 2019/1/28 10:13
 * @since v1.0
 */
public class LocationUtil {

    private static final double EARTH_RADIUS = 637_1393.00D;
    private static final double RADIAN = Math.PI / 180.00D;
    private static final double HALF = 0.5D;

    /**
     * 经纬度计算两个点的之间的距离
     *
     * @param lat1 纬度
     * @param lon1 精度
     * @param lat2 纬度
     * @param lon2 精度
     * @return 返回double 类型的距离，向上进行四舍五入，距离精确到厘米，单位为米
     */
    public static double distanceOf(double lat1, double lon1, double lat2, double lon2) {
        double x, y, a, b, distance;
        lat1 *= RADIAN;
        lat2 *= RADIAN;
        x = lat1 - lat2;
        y = lon1 - lon2;
        y *= RADIAN;
        a = Math.sin(x * HALF);
        b = Math.sin(y * HALF);
        distance = EARTH_RADIUS * Math.asin(Math.sqrt(a * a + Math.cos(lat1) * Math.cos(lat2) * b * b)) / HALF;
        return BigDecimal.valueOf(distance).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
